<script setup lang="ts">
import BySpace from "./BySpace.vue";
import ByImage from "./ByImage.vue";
import { computed } from "vue";
import { isArray } from "@tarojs/shared";

// 默认：转为string[]
const defaultFormatUrls = (e: any) => {
  if (isArray(e)) {
    return e;
  }

  return e?.split(";") || [];
};

// 默认：转为 string;string
const defaultDeformatUrls = (e: string[]) => e.join(";");

const { formatUrls, deformatUrls } = defineProps<{
  size?: string | number;
  preview?: boolean;

  // 是否显示长按菜单
  showmenu?: boolean;

  // 把modelValue格式化为 string[]格式数据
  formatUrls?: (e: any) => any[];

  // 把string
  deformatUrls?: (e: string[]) => any;
}>();

const modelValue = defineModel<any>();

const urls = computed<string[]>({
  get() {
    const { value } = modelValue;
    return (
      value ? (formatUrls || defaultFormatUrls)(modelValue.value) : []
    ) as string[];
  },
  set(val: string[] = []) {
    modelValue.value = (deformatUrls || defaultDeformatUrls)(val);
  },
});

const handleDelete = (index: number) => {
  urls.value.splice(index, 1);
  urls.value = [...urls.value];
};
</script>

<template>
  <view>
    <BySpace>
      <template v-for="(url, index) in urls" :key="index">
        <ByImage
          :url="url"
          :urls="urls"
          :size="size"
          :preview="preview"
          :showmenu="showmenu"
          delete
          @delete="handleDelete(index)"
        />
      </template>
    </BySpace>
  </view>
</template>
